package com.cskaoyan.aspect;

import com.cskaoyan.util.ValidateUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

/**
 * HJL
 * 参数检验失败响应切面
 * 全面接管所有参数校验失败的Handler方法的响应
 * 不需要在每个需要参数校验的Handler方法内都做失败响应。
 *
 */
@Aspect
@Component
public class ParamValidAspect {
    //切点
    @Pointcut("execution(* com.cskaoyan.controller.*.*(..,org.springframework.validation.BindingResult,..))")
    public void paramValidPointcut() {
    }

    /**
     * 检查参数包含BindingResult的方法，接管校验失败的响应
     * @param joinPoint
     * @return
     */
    @Around("paramValidPointcut()")
    public Object paramValidCheck(ProceedingJoinPoint joinPoint) throws Throwable {
        //校验失败响应
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof BindingResult) {
                BindingResult bindingResult = (BindingResult) arg;
                if (bindingResult.hasFieldErrors()) {
                    return ValidateUtils.valid(bindingResult);
                }
            }
        }
        //校验通过，正常响应
        return joinPoint.proceed();
    }


}
